// 多个promise异步执行.
// Promise.all();

import {logger} from "../../../../basic_util_sdk/log/logger";

function promiseEqual() {

  let p1 = Promise.resolve("1");
  let p3 = null;
  let p2 = p1.then(() => {
    p3 = Promise.resolve("2");
    return p3;
  })

  if (p1 === p2) {
    console.log("1 2 equal");
  }
  else {
    console.log("1 2 not equal");
  }

  if (p2 === p3) {
    console.log("2 3 equal");
  }
  else {
    console.log("2 3 not equal");
  }

  if (p1 === p3) {
    console.log("1 3 equal");
  }
  else {
    console.log("1 3 not equal");
  }
}

/**
 * 同一个promise await两次,内部函数只会执行一次.
 * 第一次等待后,第二次等待立马返回.
 * promise 里面的execute函数,在定义Promise之后就开始执行了,在构造阶段就执行了.
 */
async function promise_await_twice() {
  console.log("create p");
  let p = new Promise((resolve)=>{
    console.log("inside promise");
    setTimeout(()=>{
      resolve("")
    },1000);
  });
  console.log("after create p");
  console.log("before await 1");
  await p;
  console.log("after await 1");
  console.log("before await 2");
  await p;
  console.log("after await 2");
}

/**
 * 需要保证在外部没有await的情况下,连续init函数,实际的initObject操作也只进行了一次.
 */
let p_init:Promise<void>|null = null;
async function initOnce() {
  if(!p_init) {
    p_init = initObject();
  }
  await p_init;
}

async function initObject():Promise<void> {
  let p = new Promise<void>((resolve)=>{
    console.log("init");
    setTimeout(()=>{
      resolve()
    },1000);
  });
  return p;
}

function initTwice() {
  initOnce();
  initOnce();
}

//关联一个PromiseMap,确保每个函数只执行一次.
function executeOnce(fn:Function) {
  
}


/**
 * 一个promise有两个timeout,A导致resolve,B导致reject.
 */

async function twoStatePromise()  {
  logger.debug(`[promise before]`);
  let p = new Promise<void>((resolve,reject)=>{
    logger.debug(`[inner promise]`);
    setTimeout(()=>{
      logger.debug(`[success timeout]`);
        resolve();
    },1000)
    setTimeout(()=>{
      logger.debug(`[fail timeout]`);
      reject();
  },2000)
  });
  await p;
  logger.debug(`[finish]`);
}

// initTwice();
// promise_await_twice();
twoStatePromise();

